from django.shortcuts import render
from django.shortcuts import redirect
from django.http import HttpResponse
from django.template.loader import get_template
from .models import jiemaPlat,jiemaUserSet,damaPlat,damaUserSet,xunIpSet,pandaIpSet
from pyfiles import jminfo,dminfo
from django.contrib.auth import authenticate,login as xy_login
import json

# 定义login版块
def login(request):
    template = get_template('login.html')
    html = template.render({'wrong': '账号或密码错误'})
    if(request.method == 'POST'):
        recv_qq = request.POST['qq']
        recv_pwd = request.POST['pwd']
        user = authenticate(username = recv_qq, password = recv_pwd)
        if user is not None:
            xy_login(request,user)
            response = redirect("/index")
            try:
                remember = request.POST['remember']
                if remember == 'on':
                    response.set_cookie('qq', recv_qq, max_age=7 * 24 * 3600)
                    response.set_cookie('pwd', recv_pwd, max_age=7 * 24 * 3600)
            except:
                pass
            return response
        return HttpResponse(html)
    print(request.COOKIES)
    # 若之前记住了密码，则获取
    if 'qq' in request.COOKIES:
        # 获取记住的用户名
        recv_qq = request.COOKIES['qq']
        if 'pwd' in request.COOKIES:
            # 获取记住的密码
            recv_pwd = request.COOKIES['pwd']
            return render(request, 'login.html', {'qq': recv_qq, 'pwd': recv_pwd, 'checked':'checked'})
    return render(request, 'login.html',)

def index(request):
    if request.user.is_authenticated:
        return render(request, 'index.html', {'Count':'Xucooler'})
    else:
        return redirect("/")
    # return render(request, 'index.html', {'Count': 'Xucooler'})

def project(request):
    if request.user.is_authenticated:
        return render(request, 'project.html')
    else:
        return redirect("/")

def jmset(request):
    if request.user.is_authenticated:
        items = []
        jmPlats = jiemaPlat.objects.all()
        jmUserSets = jiemaUserSet.objects.filter(qq=request.user.username)
        for jmplat in jmPlats:
            for jmUserSet in jmUserSets:
                if(jmUserSet.plat == jmplat.platID):
                    a = {"platName": jmplat.platName, "count":jmUserSet.jiemaCount, "pwd":jmUserSet.jiemaPwd, "isChoice":jmUserSet.isChoice}
                    break
                else:
                    a = {"platName": jmplat.platName}
            items.append(a)
        if (request.method == "POST"):
            recv_index = request.POST['index']
            try:
                recv_model = request.POST['saveChange']
                try:
                    # 先找出该用户想设置默认的这个平台
                    which_rec = jiemaUserSet.objects.get(qq=request.user.username, plat=recv_index)
                    # 找出该用户的所有接码平台
                    recs = jiemaUserSet.objects.filter(qq = request.user.username)
                    # 将所有平台的isChoice全部变为0
                    for rec in recs:
                        rec.isChoice = 0
                        rec.save()
                    # 找出传递过来的默认平台的索引，并将之设置为默认
                    which_rec.isChoice = 1
                    which_rec.save()
                    # 传递状态码给前台，告诉他已经设置好了
                    return HttpResponse(json.dumps({'status':100}))
                except:
                    # 传递状态码给前台，出问题了
                    return HttpResponse(json.dumps({'status': 101}))
            except:
                pass
            recv_count = request.POST['count']
            recv_pwd = request.POST['pwd']
            try:
                recv_model = request.POST['save']
                recv_isChoice = request.POST['choice']
                try:
                    rec = jiemaUserSet.objects.get(qq=request.user.username, plat=recv_index)
                except:
                    rec = jiemaUserSet()
                rec.qq = request.user.username
                rec.plat = recv_index
                rec.jiemaCount = recv_count
                rec.jiemaPwd = recv_pwd
                rec.isChoice = recv_isChoice
                rec.save()
                # 保存成功之后进行查询操作
                try:
                    if(recv_index == str(1)):
                        score, money, phnum = jminfo.getdzInfo(jmPlats, recv_count, recv_pwd, recv_index)
                        print("积分：" + score)
                        resp = {'status':100,"积分" : score,"余额" : money,"批量取号数" : phnum}
                    elif (recv_index == str(2)):
                        score, money, phnum = jminfo.getmgInfo(jmPlats, recv_count, recv_pwd, recv_index)
                        print("等级：" + score)
                        resp = {'status':100,"等级": score, "余额": money, "批量取号数": phnum}
                    elif(recv_index == str(3)):
                        level, money, phnum, score = jminfo.getymInfo(jmPlats, recv_count, recv_pwd, recv_index)
                        print("等级：" + level)
                        print("积分：" + score)
                        resp = {'status':100,"积分": score, "余额": money, "批量取号数": phnum,"等级": level}
                    elif (recv_index == str(4)):
                        level, money, phnum = jminfo.getjzInfo(jmPlats, recv_count, recv_pwd, recv_index)
                        print("等级：" + level)
                        resp = {'status':100,"等级": level, "余额": money, "批量取号数": phnum}
                    print("余额：" + money)
                    print("批量取号数：" + phnum)
                    return HttpResponse(json.dumps(resp))
                except:
                    return HttpResponse(json.dumps({'status': 101}))
                    print("账号或密码错误")
            except:
                pass
            try:
                recv_model = request.POST['test']
                try:
                    # 进行查询操作
                    if(recv_index == str(1)):
                        score, money, phnum = jminfo.getdzInfo(jmPlats, recv_count, recv_pwd, recv_index)
                        print("积分：" + score)
                        resp = {'status':100,"积分" : score,"余额" : money,"批量取号数" : phnum}
                    elif (recv_index == str(2)):
                        score, money, phnum = jminfo.getmgInfo(jmPlats, recv_count, recv_pwd, recv_index)
                        print("等级：" + score)
                        resp = {'status':100,"等级": score, "余额": money, "批量取号数": phnum}
                    elif(recv_index == str(3)):
                        level, money, phnum, score = jminfo.getymInfo(jmPlats, recv_count, recv_pwd, recv_index)
                        print("等级：" + level)
                        print("积分：" + score)
                        resp = {'status':100,"积分": score, "余额": money, "批量取号数": phnum,"等级": level}
                    elif (recv_index == str(4)):
                        level, money, phnum = jminfo.getjzInfo(jmPlats, recv_count, recv_pwd, recv_index)
                        print("等级：" + level)
                        resp = {'status':100,"等级": level, "余额": money, "批量取号数": phnum}
                    print("余额：" + money)
                    print("批量取号数：" + phnum)
                    return HttpResponse(json.dumps(resp))
                except:
                    return HttpResponse(json.dumps({'status': 101}))
                    print("账号或密码错误")
            except:
                pass

        return render(request, 'jmset.html',{'items': items})
    else:
        return redirect("/")

def dmset(request):
    if request.user.is_authenticated:
        items = []
        daPlats = damaPlat.objects.all()
        daUserSets = damaUserSet.objects.filter(qq=request.user.username)
        for daplat in daPlats:
            if(daUserSets):
                for damauserset in daUserSets:
                    if(damauserset.plat == daplat.platID):
                        b = {"platName": daplat.platName, "count":damauserset.damaCount, "pwd":damauserset.damaPwd, "secretkey":damauserset.secretkey,"isChoice":damauserset.isChoice,"platID":daplat.platID}
                        break
                    else:
                        b = {"platName": daplat.platName,"platID":daplat.platID}
                items.append(b)
            else:
                b = {"platName": daplat.platName,"platID":daplat.platID}
                items.append(b)
        if(request.method == "POST"):
            recv_index = request.POST['index']
            # 保存用户的默认打码平台
            try:
                recv_model = request.POST['saveChange']
                try:
                    print(recv_index)
                    # 先找出该用户想设置默认的这个平台
                    which_rec = damaUserSet.objects.get(qq=request.user.username, plat=recv_index)
                    # 找出该用户的所有接码平台
                    recs = damaUserSet.objects.filter(qq = request.user.username)
                    # 将所有平台的isChoice全部变为0
                    for rec in recs:
                        rec.isChoice = 0
                        rec.save()
                    # 找出传递过来的默认平台的索引，并将之设置为默认
                    which_rec.isChoice = 1
                    which_rec.save()
                    # 传递状态码给前台，告诉他已经设置好了
                    return HttpResponse(json.dumps({'status':100}))
                except:
                    # 传递状态码给前台，出问题了
                    return HttpResponse(json.dumps({'status': 101}))
            except:
                pass

            # 将账号保存到数据库
            if (recv_index != str(2)):
                recv_count = request.POST['count']
                recv_pwd = request.POST['pwd']
            try:
                recv_isChoice = request.POST['choice']
                recv_model = request.POST['save']
                #除了滴滴之外的打码平台
                if(recv_index != str(2)):
                    try:
                        try:
                            rec = damaUserSet.objects.get(qq=request.user.username, plat=recv_index)
                        except:
                            rec = damaUserSet()
                        rec.qq = request.user.username
                        rec.plat = recv_index
                        rec.damaCount = recv_count
                        rec.damaPwd = recv_pwd
                        rec.isChoice = recv_isChoice
                        rec.secretkey = "null"
                        rec.save()

                    except:
                        pass
                # 滴滴打码
                else:
                    recv_sercetkey = request.POST['secretkey']
                    try:
                        rec = damaUserSet.objects.get(qq=request.user.username, plat=recv_index)
                    except:
                        rec = damaUserSet()
                    rec.qq = request.user.username
                    rec.plat = recv_index
                    rec.damaCount = "null"
                    rec.damaPwd = "null"
                    rec.isChoice = recv_isChoice
                    rec.secretkey = recv_sercetkey
                    rec.save()
                # 保存成功之后进行查询操作
                return HttpResponse(json.dumps({'status': 100}))
                pass
            except:
                pass

            # 查询操作
            try:
                recv_model = request.POST['test']
                # 联众查询
                if(recv_index == str(1)):
                    targetPlat = damaPlat.objects.get(platID=1)
                    url = targetPlat.getinfo
                    softwareId = targetPlat.softwareId
                    softwareSecret = targetPlat.softwareSecret
                    try:
                        availablePoints, userPoints = dminfo.lianzhongInfo(url,softwareId,softwareSecret,recv_count,recv_pwd)
                        resp = {'status':100,'availablePoints': availablePoints, "userPoints": userPoints}
                        print("剩余点数为：" + str(userPoints))
                        print("可用点数为：" + str(availablePoints))
                        return HttpResponse(json.dumps(resp))
                    except:
                        resp = {'status': 101}
                        return HttpResponse(json.dumps(resp))
                # 滴滴查询
                if(recv_index == str(2)):
                    targetPlat = damaPlat.objects.get(platID=2)
                    url = targetPlat.getinfo
                    secretkey = request.POST['secretkey']
                    status,user_point = dminfo.ddInfo(url,secretkey)
                    print("查询状态：" + str(status))
                    print("剩余点数：" + str(user_point))
                    if(status == 0):
                        resp = {'status': 100, 'user_point': user_point}
                    else:
                        resp = {'status': 101}
                    return HttpResponse(json.dumps(resp))
                # 极安查询
                if(recv_index == str(3)):
                    targetPlat = damaPlat.objects.get(platID=3)
                    url = targetPlat.getinfo
                    username = recv_count
                    password = recv_pwd
                    token,score = dminfo.jaInfo(url,username,password)
                    print("token:" + token)
                    print("score:" + score)
                    if(token == "none"):
                        resp = {'status': 101}
                    else:
                        resp = {'status': 100, 'userPoints': score}
                    return HttpResponse(json.dumps(resp))
                # 魔酷查询
                if (recv_index == str(4)):
                    targetPlat = damaPlat.objects.get(platID=4)
                    url = targetPlat.getinfo
                    dev_id = targetPlat.devid
                    username = recv_count
                    password = recv_pwd
                    status, token, score = dminfo.myInfo(url, username,password,dev_id)
                    print("状态码为：" + str(status))
                    print("token：" + str(token))
                    print("剩余积分：" + str(score))
                    if (status == 1):
                        resp = {'status': 100, 'userPoints': score}
                    else:
                        resp = {'status': 101}
                    return HttpResponse(json.dumps(resp))
            except:
                pass
        return render(request, 'dmset.html',{'items': items})
    else:
        return redirect("/")

def ipset(request):
    if request.user.is_authenticated:
        xunIpuserInfo = xunIpSet.objects.filter(qq=request.user.username)
        if(xunIpuserInfo):
            c={"orderA1":xunIpuserInfo[0].orderA1,"orderA2":xunIpuserInfo[0].orderA2,"aSpiderId":xunIpuserInfo[0].spiderId,"aSecret":xunIpuserInfo[0].secret,"aIschoice":xunIpuserInfo[0].isChoice}
        else:
            c = {}
        pandaIpuserInfo = pandaIpSet.objects.filter(qq=request.user.username)
        if (pandaIpuserInfo):
            d = {"orderB1": pandaIpuserInfo[0].orderB1, "orderB2": pandaIpuserInfo[0].orderB2, "bSecret": pandaIpuserInfo[0].secret,"bIschoice":pandaIpuserInfo[0].isChoice}
        else:
            d = {}
        c.update(d)
        # 保存用户的默认打码平台
        try:
            recv_model = request.POST['saveChange']
            try:
                recv_index = request.POST['index']
                if(recv_index == "1"):
                    which_rec = xunIpSet.objects.get(qq=request.user.username)
                    another = pandaIpSet.objects.get(qq=request.user.username)
                    which_rec.isChoice = 1
                    another.isChoice = 0
                else:
                    which_rec = pandaIpSet.objects.get(qq=request.user.username)
                    another = xunIpSet.objects.get(qq=request.user.username)
                    which_rec.isChoice = 1
                    another.isChoice = 0
                which_rec.save()
                another.save()
                # 传递状态码给前台，告诉他已经设置好了
                return HttpResponse(json.dumps({'status': 100}))
            except:
                # 传递状态码给前台，出问题了
                return HttpResponse(json.dumps({'status': 101}))
        except:
            pass
        # 保存数据
        if(request.method == "POST"):
            try:
                recv_model = request.POST['save']
                # 讯代理
                if(request.POST['index'] == "1"):
                    try:
                        newxunip = xunIpSet.objects.get(qq=request.user.username)
                    except:
                        newxunip = xunIpSet()
                    newxunip.qq = request.user.username
                    newxunip.secret = request.POST['secret']
                    newxunip.spiderId = request.POST['spiderId']
                    newxunip.orderA1 = request.POST['betterip']
                    newxunip.orderA2 = request.POST['normalip']
                    newxunip.isChoice = request.POST['choice']
                    newxunip.save()
                # 熊猫代理
                if (request.POST['index'] == "2"):
                    try:
                        newpandaip = pandaIpSet.objects.get(qq=request.user.username)
                    except:
                        newpandaip = pandaIpSet()
                    newpandaip.qq = request.user.username
                    newpandaip.secret = request.POST['secret']
                    newpandaip.orderB1 = request.POST['betterip']
                    newpandaip.orderB2 = request.POST['normalip']
                    newpandaip.isChoice = request.POST['choice']
                    newpandaip.save()
                return HttpResponse(json.dumps({'status': 100}))
            except:
                return HttpResponse(json.dumps({'status': 101}))
        return render(request, 'ipset.html',c)
    else:
        return redirect("/")

def record(request):
    if request.user.is_authenticated:
        return render(request, 'record.html')
    else:
        return redirect("/")

def help(request):
    if request.user.is_authenticated:
        return render(request, 'help.html')
    else:
        return redirect("/")

def author(request):
    if request.user.is_authenticated:
        return render(request, 'author.html')
    else:
        return redirect("/")
